package com.controller;

import com.conf.BaseServlet;
import com.etonepay.b2c.utils.StringUtil;
import com.model.TSystemAccount;
import com.model.TUserInfo;
import com.shanpayapi.cn.Constant;
import com.shanpayapi.cn.exception.PayException;
import com.shanpayapi.cn.util.Md5Util;
import com.shanpayapi.cn.util.ShanPayUtil;
import com.util.OrderNoUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: TZJ
 * @create: 2017-12-01 15:31
 */
@Controller
@RequestMapping("demo")
public class ShanpayController extends BaseServlet {

    private static final long serialVersionUID = 1L;

    @RequestMapping(value = "/pay", method = { RequestMethod.GET,
            RequestMethod.POST })
    public ModelAndView pay(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        String userNumber = request.getParameter("userToken");
        String merOrderNum = OrderNoUtil.getChargeNo();
        String tranAmt = StringUtil.checkNullString(request
                .getParameter("tranAmt"));
        String userId = StringUtil.checkNullString(request
                .getParameter("userId"));

        TSystemAccount systemAccount = new TSystemAccount();
        systemAccount.setTsaType(1);
        systemAccount.setTsaUserType(3);
        systemAccount.setTsaUserId(Integer.parseInt(userId));
        systemAccount.setTsaMoney(Double.parseDouble(tranAmt));
        systemAccount.setTsaStatus(2);
        systemAccount.setTsaDesc("种子期权充值"+tranAmt);
        systemAccount.setTsaChargeCode(merOrderNum);
        tSystemAccountMapper.insertSelective(systemAccount);

        Map<String, Object> requestParams = getParameter(userNumber,merOrderNum,tranAmt,userId);

        String signMd5 = ShanPayUtil.buildRequestParaShan(requestParams, Constant.HKEY);

        requestParams.put("sign", signMd5);

        Map<String,Object> model = new HashMap<>();
        model.put("data", requestParams);
        model.put("gateway_new", Constant.GATEWAY_NEW);
        ModelAndView modelAndView = new ModelAndView("shanpay.jsp",model);
        return modelAndView;
//        request.setAttribute("data", requestParams);
//        request.setAttribute("gateway_new", Constant.GATEWAY_NEW);
//        request.getRequestDispatcher("shanpay").forward(request, response);
    }


    /**
     * Function：获取request中的订单信息<br>
     * <p>
     * MethodName：getParameter<br>
     * <p>
     * Date：2016年6月26日上午10:30:59<br>
     *
     * @
     */
    private Map<String, Object> getParameter( String userNumber, String merOrderNum, String tranAmt, String userId) throws PayException {

        /**************************请求参数**************************/
        //商户订单号
        String out_order_no = merOrderNum;
        //订单名称
        String subject = "购买";
        //付款金额
        String total_fee = tranAmt;
        //订单描述
        String body = "种子期权充值";
        if (out_order_no == null || subject == null || total_fee == null) {
            throw new PayException("必要参数不能为空!");
        }
        //服务器异步通知页面路径
        String notify_url = Constant.NOTIFY;
        if ("".equals(notify_url)) {
            throw new PayException("notify_url不能为空!");
        }
        //需http://格式的完整路径，不能加?id=123这类自定义参数
        //页面跳转同步通知页面路径
        String return_url = Constant.RETURN;
        if ("".equals(return_url)) {
            throw new PayException("return_url不能为空!");
        }
        if ("".equals(Constant.USER_SEL)) {
            throw new PayException("商户号不能为空!");
        }
        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("body", body);
        parameter.put("notify_url", Constant.NOTIFY);
        parameter.put("out_order_no", out_order_no);
        parameter.put("partner", Constant.HPARTNE);
        parameter.put("return_url", Constant.RETURN);
        parameter.put("subject", subject);
        parameter.put("total_fee", total_fee);
        parameter.put("user_seller", Constant.USER_SEL);
        return parameter;
    }

    /**
     * 异步通知
     * @param:
     * @return:
     * @author:TZJ
     * @date: 2017/12/1 16:28
     */
    @RequestMapping(value = "/notifyUrl", method = { RequestMethod.GET,
            RequestMethod.POST })
    public ModelAndView notifyUrl(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException{
        boolean shanNotify = md5VerifyShan(request);
        String result = "success";
        if(shanNotify){
            if("TRADE_SUCCESS".equals(request.getParameter("trade_status"))){
				 /*
				加入您的入库及判断代码;
				判断返回金额与实金额是否想同;
				判断订单当前状态;
				完成以上才视为支付成功
				*/
                //商户订单号
                String out_trade_no = request.getParameter("out_order_no");
                //环球汇交易号
                String trade_no =  request.getParameter("trade_no");
                //价格
                String price =  request.getParameter("total_fee");

                //入金操作
                List<TSystemAccount> tSystemAccountList = tSystemAccountMapper.selectByChargeCode(out_trade_no);
                if(tSystemAccountList.size() == 0){
                    result =  "fail";
                }else{
                    TSystemAccount systemAccount = tSystemAccountList.get(0);
                    if(systemAccount.getTsaMoney() != Double.parseDouble(price) ){
                        result =  "fail";
                    }else{
                        if(systemAccount.getTsaStatus() == 2){
                            TUserInfo tUserInfo = tUserInfoMapper.selectByPrimaryKey(systemAccount.getTsaUserId());
                            systemAccount.setTsaStatus(1);
                            systemAccount.setTsaStartMoney(tUserInfo.getTuiBalance());
                            systemAccount.setTsaEndMoney(tUserInfo.getTuiBalance() + Double.parseDouble(price));
                            tSystemAccountMapper.updateByPrimaryKeySelective(systemAccount);

                            tUserInfo.setTuiBalance(tUserInfo.getTuiBalance() + Double.parseDouble(price));
                            tUserInfoMapper.updateByPrimaryKeySelective(tUserInfo);
                        }
                    }
                }
            }
        }else {
            //验证失败
            result =  "fail";//请不要修改或删除
        }

//        ModelAndView modelAndView = null;
//        if(result.equalsIgnoreCase("success")){
//            modelAndView = new ModelAndView("chargeSuccess.html");
//        }else{
//            modelAndView = new ModelAndView("chongzhiError.html");
//        }

        Map<String,Object> model = new HashMap<>();
        model.put("result_info", result);
        ModelAndView modelAndView = new ModelAndView("notify_url.jsp",model);
        return modelAndView;

//        if(result.equalsIgnoreCase("success")){
//            request.getRequestDispatcher("chargeSuccess.html").forward(request,response);
//        }else{
//            request.getRequestDispatcher("chongzhiError.html").forward(request,response);
//        }
//        request.setAttribute("result_info", result);
//        request.getRequestDispatcher("notify_url.jsp").forward(request,response);

    }

    /**
     * 同步通知
     * @param:
     * @return:
     * @author:TZJ
     * @date: 2017/12/1 16:32
     */
    @RequestMapping(value = "/returnUrl", method = { RequestMethod.GET,
            RequestMethod.POST })
    public ModelAndView returnUrl(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException{
        boolean shanNotify = md5VerifyShan(request);
        System.out.println("shanNotify:"+shanNotify);
        String result = "success";
        if(shanNotify){
            if("TRADE_SUCCESS".equals(request.getParameter("trade_status"))){
				 /*
				加入您的入库及判断代码;
				判断返回金额与实金额是否想同;
				判断订单当前状态;
				完成以上才视为支付成功
				*/
                //商户订单号
                String out_trade_no = request.getParameter("out_order_no");
                //环球汇交易号
                String trade_no =  request.getParameter("trade_no");
                //价格
                String price =  request.getParameter("total_fee");

                //入金操作
                List<TSystemAccount> tSystemAccountList = tSystemAccountMapper.selectByChargeCode(out_trade_no);
                if(tSystemAccountList.size() == 0){
                    result =  "fail";
                }else{
                    TSystemAccount systemAccount = tSystemAccountList.get(0);
                    if(systemAccount.getTsaMoney() != Double.parseDouble(price) ){
                        result =  "fail";
                    }else{
                        if(systemAccount.getTsaStatus() == 2){
                            TUserInfo tUserInfo = tUserInfoMapper.selectByPrimaryKey(systemAccount.getTsaUserId());
                            systemAccount.setTsaStatus(1);
                            systemAccount.setTsaStartMoney(tUserInfo.getTuiBalance());
                            systemAccount.setTsaEndMoney(tUserInfo.getTuiBalance() + Double.parseDouble(price));
                            tSystemAccountMapper.updateByPrimaryKeySelective(systemAccount);

                            tUserInfo.setTuiBalance(tUserInfo.getTuiBalance() + Double.parseDouble(price));
                            tUserInfoMapper.updateByPrimaryKeySelective(tUserInfo);
                        }

                    }
                }
            }
        }else {
            //验证失败
            result =  "fail";//请不要修改或删除
        }
//        Map<String,Object> model = new HashMap<>();
//        model.put("result_info", result);
//        ModelAndView modelAndView = null;
//        if(result.equalsIgnoreCase("success")){
//            modelAndView = new ModelAndView("chargeSuccess.html");
//        }else{
//            modelAndView = new ModelAndView("chongzhiError.html");
//        }

        Map<String,Object> model = new HashMap<>();
        model.put("result_info", result);
        ModelAndView modelAndView = new ModelAndView("return_url.jsp",model);
        return modelAndView;

//        request.setAttribute("result_info", result);
//        request.getRequestDispatcher("return_url.jsp").forward(request,response);
    }


    public boolean md5VerifyShan(HttpServletRequest request) throws UnsupportedEncodingException, PayException{
        request.setCharacterEncoding("UTF-8");
        String out_order_no = request.getParameter("out_order_no");
        System.out.println("out_order_no:"+out_order_no);
        if("".equals(out_order_no)||out_order_no==null){
            throw new PayException("out_order_no不能为空");
        }
        String total_fee = request.getParameter("total_fee");
        if("".equals(total_fee)||total_fee==null){
            throw new PayException("total_fee不能为空");
        }
        String trade_status  = request.getParameter("trade_status");
        if("".equals(total_fee)||total_fee==null){
            throw new PayException("trade_status不能为空");
        }
        String sign = request.getParameter("sign");
        if("".equals(total_fee)||total_fee==null){
            throw new PayException("sign不能为空");
        }
        String key = Constant.HKEY;
        String pid = Constant.HPARTNE;
        Md5Util md5Util = new Md5Util();
        String signMd5 = md5Util.encode(out_order_no+total_fee+trade_status+pid+key, null);
        System.out.println("signMd5:"+signMd5);
        if(signMd5.equals(sign)){
            return true;
        }
        return false;
    }
}
